#include "myhead.h"

int udpsock;//套接字标识符

void *func(void *arg)
{
    struct sockaddr_in conaddr;
    int size=sizeof(conaddr);
    char buf[20]="";
    while(1)
    {
        bzero(buf,sizeof(buf));
        int ret = recvfrom(udpsock,buf,sizeof(buf),0,(struct sockaddr *) &conaddr,&size);
        if(ret==-1)
        {
            perror("recv");
            return NULL;
        }
        else  if(ret==0)
        {
            exit(-1);
        }
        printf("%s\n",buf);
    }
}
int main()
{
    udpsock=socket(AF_INET,SOCK_DGRAM,0);
    if(udpsock==-1)
    {
        perror("socket\n");
        return -1;
    }

    //允许udp广播信息
    int opt=1;
    setsockopt(udpsock,SOL_SOCKET,SO_BROADCAST,&opt,sizeof(opt));

    //bind
    struct sockaddr_in bindaddr;//结构体里面要有ip和端口
    bindaddr.sin_family=AF_INET;//选择地址协议ipv4
    inet_pton(AF_INET, "192.168.72.255", &bindaddr.sin_addr);//ip
    bindaddr.sin_port=htons(10086);//端口

    int ret = bind(udpsock,(struct sockaddr *)&bindaddr,sizeof(struct sockaddr_in));
    if(ret==-1)
    {
        perror("bind");
        return -1;
    }

    //设置要连接的ip和端口
    struct sockaddr_in conaddr;//结构体里面要有ip和端口
    conaddr.sin_family=PF_INET;//选择地址协议ipv4
    //conaddr.sin_addr.s_addr=inet_addr("192.168.72.52");//小转大：inet_addr inet_pton inet_aton
    //一般用inet_pton
    if (inet_pton(AF_INET, "192.168.72.52", &conaddr.sin_addr) != 1) 
    {
        /* 返回 0 表示格式错，-1 表示 errno 错 */
        perror("inet_pton");
        exit(1);
    }
    conaddr.sin_port=htons(10000);//端口

    //创建两个线程
    pthread_t id1;
    pthread_create(&id1,NULL,func,NULL);

    char buf[20]="";
    while (1)
    {
        bzero(buf,sizeof(buf));
        scanf("%s",buf);
        ret = sendto(udpsock,buf,strlen(buf),0,(struct sockaddr *)&conaddr,sizeof(struct sockaddr_in));
        if(ret==-1)
        {
            perror("send");
            return -1;
        }
    }
    close(udpsock);
    pthread_join(id1,NULL);
}